using System.Collections;
using System.Linq;
using UnityEngine;

public class DoorController : MonoBehaviour
{
    private Transform transformDoor;
    private Transform transformLeftDoor;
    private Transform transformRightDoor;
    private bool isSingleDoor = true;

    private bool isOpen = false;
    [Header("开关门速度")]
    [Tooltip("值越大速度越慢")]
    public float speed = 10;
    [Header("自动关门")]
    public bool autoClose = true;

    private Quaternion quaternionOpen = Quaternion.Euler(0, 90.0f, 0);
    private Quaternion quaternionClose = Quaternion.Euler(0, 0, 0);

    void Awake()
    {
        var transformDoors = transform.parent.GetComponentsInChildren<Transform>();
        this.transformDoor = transformDoors.Where(x => x.CompareTag(Defines.Door)).FirstOrDefault();

        if (transformDoor == null)
        {
            // 是双开门
            this.isSingleDoor = false;
            this.transformLeftDoor = transformDoors.Where(x => x.CompareTag(Defines.DoorLeft)).FirstOrDefault();
            this.transformRightDoor = transformDoors.Where(x => x.CompareTag(Defines.DoorRight)).FirstOrDefault();
        }

        var boxCollider = gameObject.AddComponent<BoxCollider>();
        boxCollider.isTrigger = true;
        boxCollider.center = Vector3.zero;
        boxCollider.size = new Vector3(boxCollider.size.x + 0.5f, boxCollider.size.y + 0.5f, boxCollider.size.z + 3.0f);
    }
    
    void OnTriggerEnter(Collider other)
    {
        if (!this.isOpen)
        {
            this.isOpen = true;
            Core();
        }
    }

    void OnTriggerExit(Collider other)
    {
        if (this.autoClose && this.isOpen)
        {
            this.isOpen = false;
            Core();
        }
    }

    private void Core()
    {
        StopRotation();
        StartCoroutine(nameof(SmoothRotation));
    }

    IEnumerator SmoothRotation()
    {
        float elapsed = 0f;

        while (elapsed < speed)
        {
            elapsed += Time.deltaTime;
            float t = elapsed / speed;  // t 从0渐变到1

            if (this.isSingleDoor)
            {
                transformDoor.localRotation = Quaternion.Slerp(transformDoor.localRotation, this.isOpen ? quaternionOpen : quaternionClose, t);
            }
            else
            {
                transformLeftDoor.localRotation = Quaternion.Slerp(transformLeftDoor.localRotation, this.isOpen ? quaternionOpen : quaternionClose, t);
                transformRightDoor.localRotation = Quaternion.Slerp(transformRightDoor.localRotation, this.isOpen ? quaternionOpen : quaternionClose, t);
            }

            if (t > 1)
            {
                break;
            }

            yield return null;
        }
    }

    private void StopRotation()
    {
        StopCoroutine(nameof(SmoothRotation));
    }
}
